{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Demo of EPIC Distance\n",
    "\n",
    "EPIC distance measures the dissimilarity between reward functions. It works by mapping reward functions to a canonical representative that is invariant to potential shaping, then computing the Pearson correlation between the canonicalized reward functions. In this notebook, we compute EPIC distance between reward functions in a simple PointMass environment.\n",
    "\n",
    "For more information, see the accompanying [paper](https://arxiv.org/abs/2006.13900). This notebook will produce a subset of the heatmap in Figure 2(a)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "First, we install the `evaluating_rewards` library and its dependencies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install library if it's not already installed\n",
    "import importlib\n",
    "spec = importlib.util.find_spec(\"evaluating_rewards\")\n",
    "if spec is None:\n",
    "    !pip install --quiet git+git://github.com/HumanCompatibleAI/evaluating-rewards"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports\n",
    "\n",
    "Now, we import some standard RL and ML dependencies, and relevant modules from our `evaluating_rewards` library."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Turn off distracting warnings and logging\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "import tensorflow as tf\n",
    "import logging\n",
    "logging.getLogger(\"tensorflow\").setLevel(logging.CRITICAL)\n",
    "\n",
    "# Import rest of the dependencies\n",
    "import gym\n",
    "import pandas as pd\n",
    "from stable_baselines.common import vec_env\n",
    "\n",
    "from evaluating_rewards import datasets, serialize\n",
    "from evaluating_rewards.analysis import util\n",
    "from evaluating_rewards.distances import epic_sample, tabular\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Configuration\n",
    "\n",
    "In this section, we specify some hyperparameters, including the environment to load (PointMass) and models to compare."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "n_samples = 512  # number of samples to take final expectation over\n",
    "n_mean_samples = 512  # number of samples to use to canonicalize potential\n",
    "env_name = \"evaluating_rewards/PointMassLine-v0\"  # the environment to compare in\n",
    "# The reward models to load.\n",
    "model_kinds = (\n",
    "    \"evaluating_rewards/PointMassSparseWithCtrl-v0\",\n",
    "    \"evaluating_rewards/PointMassDenseWithCtrl-v0\",\n",
    "    \"evaluating_rewards/PointMassGroundTruth-v0\"\n",
    ")\n",
    "seed = 42  # make results deterministic"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load Models\n",
    "\n",
    "Here, we load the reward models. For simplicity, we load hardcoded reward models, and so specify a `\"dummy\"` reward path. `serialize` also supports loading learned reward models produced by other packages like [imitation](http://github.com/humancompatibleai/imitation). You can also register your own loaders with `serialize`, or load reward models by another mechanism -- the only requirement is they must satisfy the `evaluating_rewards.rewards.RewardModel` interface."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "venv = vec_env.DummyVecEnv([lambda: gym.make(env_name)])\n",
    "sess = tf.Session()\n",
    "with sess.as_default():\n",
    "    tf.set_random_seed(seed)\n",
    "    models = {kind: serialize.load_reward(reward_type=kind, reward_path=\"dummy\", venv=venv) \n",
    "              for kind in model_kinds}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Compute EPIC Distance\n",
    "\n",
    "Finally, we canonicalize the rewards and compute the Pearson distance between canonicalized rewards, producing the EPIC distance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Visitation distribution (obs,act,next_obs) is IID sampled from spaces\n",
    "with datasets.transitions_factory_iid_from_sample_dist_factory(\n",
    "    obs_dist_factory=datasets.sample_dist_from_space,\n",
    "    act_dist_factory=datasets.sample_dist_from_space,\n",
    "    obs_kwargs={\"space\": venv.observation_space},\n",
    "    act_kwargs={\"space\": venv.action_space},\n",
    "    seed=seed,\n",
    ") as iid_generator:\n",
    "    batch = iid_generator(n_samples)\n",
    "\n",
    "with datasets.sample_dist_from_space(venv.observation_space, seed=seed+1) as obs_dist:\n",
    "    next_obs_samples = obs_dist(n_mean_samples)\n",
    "with datasets.sample_dist_from_space(venv.action_space, seed=seed+2) as act_dist:\n",
    "    act_samples = act_dist(n_mean_samples)\n",
    "    \n",
    "# Finally, let's compute the EPIC distance between these models.\n",
    "# First, we'll canonicalize the rewards.\n",
    "with sess.as_default():\n",
    "    deshaped_rew = epic_sample.sample_canon_shaping(\n",
    "        models=models,\n",
    "        batch=batch,\n",
    "        next_obs_samples=next_obs_samples,\n",
    "        act_samples=act_samples,\n",
    "        # You can also specify the discount rate and the type of norm,\n",
    "        # but defaults are fine for most use cases.\n",
    "    )\n",
    "\n",
    "# Now, let's compute the Pearson distance between these canonicalized rewards.\n",
    "# The canonicalized rewards are quantized to `n_samples` granularity, so we can\n",
    "# then compute the Pearson distance on this (finite approximation) exactly.\n",
    "epic_distance = util.cross_distance(deshaped_rew, deshaped_rew, tabular.pearson_distance, parallelism=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Results\n",
    "\n",
    "The `Sparse` and `Dense` rewards are equivalent, differing only up to shaping, and accordingly have zero EPIC distance. The `GroundTruth` reward is not equivalent and so has a significant EPIC distance. See section 6.1 of the [https://arxiv.org/pdf/2006.13900.pdf](paper) for further information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>DenseWithCtrl</th>\n",
       "      <th>GroundTruth</th>\n",
       "      <th>SparseWithCtrl</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>DenseWithCtrl</th>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.571963</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>GroundTruth</th>\n",
       "      <td>0.571963</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.571963</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>SparseWithCtrl</th>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.571963</td>\n",
       "      <td>0.000173</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                DenseWithCtrl  GroundTruth  SparseWithCtrl\n",
       "DenseWithCtrl        0.000000     0.571963        0.000000\n",
       "GroundTruth          0.571963     0.000000        0.571963\n",
       "SparseWithCtrl       0.000000     0.571963        0.000173"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "epic_df = pd.Series(epic_distance).unstack()\n",
    "epic_df.index = epic_df.index.str.replace(r'evaluating_rewards/PointMass(.*)-v0', r'\\1')\n",
    "epic_df.columns = epic_df.columns.str.replace(r'evaluating_rewards/PointMass(.*)-v0', r'\\1')\n",
    "epic_df"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Edit Metadata",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  },
  "nbreg": {
   "diff_ignore": [
    "/metadata/language_info/version"
   ]
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
